package com.cw.starter.kafka.producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import com.alibaba.fastjson2.JSONObject;
import com.cw.starter.kafka.constant.KafkaMessageDto;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * kafka消息发送类
 * @author chenw
 * @version 5.0 since 2020-01-13
 */
@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
    /**
     * 发送kafka消息
     * TODO 发送失败，自动重试3次
     * @param messageDto
     */
    public void send(String topic,KafkaMessageDto messageDto) {
        log.info("准备发送消息为：{}", JSONObject.toJSONString(messageDto));
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, JSONObject.toJSONString(messageDto));
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info("业务流水号：" + messageDto.getSerialNo() + " " + topic + " - 生产者 发送消息失败：" + throwable.getMessage());
                //重试或抛异常
            }

            @Override
            public void onSuccess(SendResult<String, Object> sendResult) {
                //成功的处理
                log.info("业务流水号：" + messageDto.getSerialNo() + " " + topic + " - 生产者 发送消息成功：" + sendResult.toString());
            }
        });


    }
}